import React, { useEffect, useState } from 'react';
import { Card, Statistic, Row, Col, Progress } from 'antd';
import { getCLS, getFID, getFCP, getLCP, getTTFB } from 'web-vitals';

/**
 * Web Vitals性能指标接口
 */
interface VitalsMetrics {
  cls: number | null;
  fid: number | null;
  fcp: number | null;
  lcp: number | null;
  ttfb: number | null;
}

/**
 * 性能评分标准
 */
const PERFORMANCE_THRESHOLDS = {
  CLS: { good: 0.1, poor: 0.25 }, // 布局偏移
  FID: { good: 100, poor: 300 },  // 首次输入延迟
  FCP: { good: 1800, poor: 3000 }, // 首次内容绘制
  LCP: { good: 2500, poor: 4000 }, // 最大内容绘制
  TTFB: { good: 600, poor: 1400 }  // 首字节时间
};

/**
 * 性能评分计算
 */
const getPerformanceScore = (value: number, thresholds: { good: number; poor: number }): 'good' | 'needs-improvement' | 'poor' => {
  if (value <= thresholds.good) return 'good';
  if (value <= thresholds.poor) return 'needs-improvement';
  return 'poor';
};

/**
 * 性能评分颜色
 */
const getScoreColor = (score: string): string => {
  switch (score) {
    case 'good': return '#52c41a';
    case 'needs-improvement': return '#faad14';
    case 'poor': return '#ff4d4f';
    default: return '#d9d9d9';
  }
};

/**
 * Web Vitals性能监控组件
 */
const WebVitalsMonitor: React.FC = () => {
  const [metrics, setMetrics] = useState<VitalsMetrics>({
    cls: null,
    fid: null,
    fcp: null,
    lcp: null,
    ttfb: null
  });

  const [isVisible, setIsVisible] = useState(false);

  useEffect(() => {
    // 仅在开发环境显示性能监控
    if (process.env.NODE_ENV === 'production') return;

    const handleKeyDown = (e: KeyboardEvent) => {
      // Ctrl + Shift + P 显示/隐藏性能监控
      if (e.ctrlKey && e.shiftKey && e.key === 'P') {
        e.preventDefault();
        setIsVisible(prev => !prev);
      }
    };

    window.addEventListener('keydown', handleKeyDown);

    // 收集性能指标
    const collectMetrics = () => {
      const vitals: VitalsMetrics = {
        cls: null,
        fid: null,
        fcp: null,
        lcp: null,
        ttfb: null
      };

      getCLS((metric) => {
        vitals.cls = metric.value;
        setMetrics({ ...vitals });
      });

      getFID((metric) => {
        vitals.fid = metric.value;
        setMetrics({ ...vitals });
      });

      getFCP((metric) => {
        vitals.fcp = metric.value;
        setMetrics({ ...vitals });
      });

      getLCP((metric) => {
        vitals.lcp = metric.value;
        setMetrics({ ...vitals });
      });

      getTTFB((metric) => {
        vitals.ttfb = metric.value;
        setMetrics({ ...vitals });
      });
    };

    collectMetrics();

    return () => {
      window.removeEventListener('keydown', handleKeyDown);
    };
  }, []);

  // 计算总体性能评分
  const overallScore = React.useMemo(() => {
    const scores = [
      metrics.cls !== null ? getPerformanceScore(metrics.cls, PERFORMANCE_THRESHOLDS.CLS) : null,
      metrics.fid !== null ? getPerformanceScore(metrics.fid, PERFORMANCE_THRESHOLDS.FID) : null,
      metrics.fcp !== null ? getPerformanceScore(metrics.fcp, PERFORMANCE_THRESHOLDS.FCP) : null,
      metrics.lcp !== null ? getPerformanceScore(metrics.lcp, PERFORMANCE_THRESHOLDS.LCP) : null,
      metrics.ttfb !== null ? getPerformanceScore(metrics.ttfb, PERFORMANCE_THRESHOLDS.TTFB) : null
    ].filter(Boolean);

    if (scores.length === 0) return 0;

    const goodCount = scores.filter(score => score === 'good').length;
    return Math.round((goodCount / scores.length) * 100);
  }, [metrics]);

  if (!isVisible || process.env.NODE_ENV === 'production') return null;

  return (
    <div style={{
      position: 'fixed',
      top: '10px',
      right: '10px',
      width: '400px',
      zIndex: 9999,
      boxShadow: '0 4px 12px rgba(0,0,0,0.15)'
    }}>
      <Card
        title="Web Vitals 性能监控"
        size="small"
        extra={
          <span style={{ fontSize: '12px', color: '#666' }}>
            按 Ctrl+Shift+P 隐藏
          </span>
        }
      >
        {/* 总体性能评分 */}
        <div style={{ marginBottom: '16px' }}>
          <Row align="middle">
            <Col span={12}>
              <span style={{ fontSize: '14px', fontWeight: 'bold' }}>总体评分</span>
            </Col>
            <Col span={12}>
              <Progress
                type="circle"
                size={60}
                percent={overallScore}
                strokeColor={overallScore >= 80 ? '#52c41a' : overallScore >= 60 ? '#faad14' : '#ff4d4f'}
              />
            </Col>
          </Row>
        </div>

        {/* 详细性能指标 */}
        <Row gutter={[8, 8]}>
          {/* CLS - 布局偏移 */}
          <Col span={12}>
            <Card size="small">
              <Statistic
                title="CLS"
                value={metrics.cls || 0}
                precision={3}
                suffix=""
                valueStyle={{ color: metrics.cls ? getScoreColor(getPerformanceScore(metrics.cls, PERFORMANCE_THRESHOLDS.CLS)) : '#d9d9d9' }}
              />
              <div style={{ fontSize: '11px', color: '#666', marginTop: '4px' }}>
                布局偏移
              </div>
            </Card>
          </Col>

          {/* FID - 首次输入延迟 */}
          <Col span={12}>
            <Card size="small">
              <Statistic
                title="FID"
                value={metrics.fid || 0}
                precision={0}
                suffix="ms"
                valueStyle={{ color: metrics.fid ? getScoreColor(getPerformanceScore(metrics.fid, PERFORMANCE_THRESHOLDS.FID)) : '#d9d9d9' }}
              />
              <div style={{ fontSize: '11px', color: '#666', marginTop: '4px' }}>
                首次输入延迟
              </div>
            </Card>
          </Col>

          {/* FCP - 首次内容绘制 */}
          <Col span={12}>
            <Card size="small">
              <Statistic
                title="FCP"
                value={metrics.fcp || 0}
                precision={0}
                suffix="ms"
                valueStyle={{ color: metrics.fcp ? getScoreColor(getPerformanceScore(metrics.fcp, PERFORMANCE_THRESHOLDS.FCP)) : '#d9d9d9' }}
              />
              <div style={{ fontSize: '11px', color: '#666', marginTop: '4px' }}>
                首次内容绘制
              </div>
            </Card>
          </Col>

          {/* LCP - 最大内容绘制 */}
          <Col span={12}>
            <Card size="small">
              <Statistic
                title="LCP"
                value={metrics.lcp || 0}
                precision={0}
                suffix="ms"
                valueStyle={{ color: metrics.lcp ? getScoreColor(getPerformanceScore(metrics.lcp, PERFORMANCE_THRESHOLDS.LCP)) : '#d9d9d9' }}
              />
              <div style={{ fontSize: '11px', color: '#666', marginTop: '4px' }}>
                最大内容绘制
              </div>
            </Card>
          </Col>

          {/* TTFB - 首字节时间 */}
          <Col span={24}>
            <Card size="small">
              <Statistic
                title="TTFB"
                value={metrics.ttfb || 0}
                precision={0}
                suffix="ms"
                valueStyle={{ color: metrics.ttfb ? getScoreColor(getPerformanceScore(metrics.ttfb, PERFORMANCE_THRESHOLDS.TTFB)) : '#d9d9d9' }}
              />
              <div style={{ fontSize: '11px', color: '#666', marginTop: '4px' }}>
                首字节时间
              </div>
            </Card>
          </Col>
        </Row>

        {/* 性能建议 */}
        <div style={{ marginTop: '12px', fontSize: '12px', color: '#666' }}>
          <strong>优化建议：</strong>
          <ul style={{ margin: '4px 0', paddingLeft: '16px' }}>
            {metrics.cls && metrics.cls > PERFORMANCE_THRESHOLDS.CLS.good && (
              <li>优化布局偏移：避免动态调整元素尺寸</li>
            )}
            {metrics.fid && metrics.fid > PERFORMANCE_THRESHOLDS.FID.good && (
              <li>优化交互响应：减少JavaScript执行时间</li>
            )}
            {metrics.fcp && metrics.fcp > PERFORMANCE_THRESHOLDS.FCP.good && (
              <li>优化首次渲染：减少首屏资源大小</li>
            )}
            {metrics.lcp && metrics.lcp > PERFORMANCE_THRESHOLDS.LCP.good && (
              <li>优化最大内容渲染：优化图片和字体加载</li>
            )}
            {metrics.ttfb && metrics.ttfb > PERFORMANCE_THRESHOLDS.TTFB.good && (
              <li>优化服务器响应：使用CDN和缓存策略</li>
            )}
          </ul>
        </div>
      </Card>
    </div>
  );
};

export default WebVitalsMonitor;